$(function() {
    var rows_delete = 0;
    var rows_click = 0;
    var mode = "add";
    var m_id = 0;
    var url = 'controls/stock_model.php';
    var pid = 0;
    var cost=0;
    LoadData('','',0,_cdate,_cdate,'');

   	var checkDate = $('.btndate1').datepicker().on('changeDate', function(ev) {
	  checkDate.hide();
	}).data('datepicker');
	
	var checkDate2 = $('.btndate2').datepicker().on('changeDate', function(ev) {
	  checkDate2.hide();
	}).data('datepicker');
	
	$("#txtDateFrom_s,#txtDateTo_s").val(_cdate);
    $(".txtreceive_no").live('keypress', function(e) {

        if (e.which !== 8 && e.which !== 0 && (e.which < 48 || e.which > 57)) {
            return false;
        }
    });
	
	
    $("input[name=txtro_amt]").live('keyup',function(event){
        var iamt = $(this).val(); 
        
        var rowSelect = $(this).parent().parent();
        
        var iprice = new Number(rowSelect.find("td").eq(5).html().replace(',','').replace(',',''));
        
          //Get Discount AMt
        var idiscount = new Number(rowSelect.find("td").eq(6).html().replace(',','').replace(',',''));
        
        var itotal= new Number((parseFloat(iprice) * parseFloat(iamt)) -parseFloat(idiscount) );
        rowSelect.find("td").eq(7).html(  ( itotal.toFixed(2) ));
    });

    $("#btnSave").live('click', function(e) {
		 
        $("#txtRO").jqBootstrapValidation({preventSubmit: false,
            submitSuccess: function($form, event) {
                event.preventDefault();
            }
        });
       // if ($("#txtRO").val()==""){return;}
        //var cells = [];
        if (mode === "edit") {
            var list = [];
             
            var total_cost=0;
            var total_discount=0;
            
            $('#table_detail tbody tr').each(function() {
                var ro_amt = $(this).find("input[name=txtro_amt]").val().replace(',','').replace(',',''); 
                var row_data = $('#table_detail').dataTable().fnGetData(this);
                
                list.push({'id': row_data[1],
                            'amt': ro_amt  });
                        
                var iprice = new Number($(this).find("td").eq(5).html().replace(',','').replace(',',''));  
                var idiscount = new Number($(this).find("td").eq(6).html().replace(',','').replace(',',''));
                
                total_cost += (parseFloat(iprice) * parseInt(ro_amt) );
                total_discount += parseFloat(idiscount);
            });
       
           // var no = $("#txtRO").val();
           
             $("#popup").modal('hide');

            $.ajax({
                type: 'POST',
                cache: false,
                url: url,
                data: {"m": "update_receive", "mid": m_id,   "list": list ,"total":total_cost},
                success: function(data) {
                    var obj = eval('(' + data + ')');
                     $("#resultData").dataTable().fnUpdate(obj,rows_click);
                  
                }
            }); 

        }  

        $("#txtRO").jqBootstrapValidation("destroy");
    });
    
    $(".btnCheck").live('click', function() {
		$("#btnCancel").html("ยกเลิก");
        $("#txtRO").val("");
        $("#txtRO").show();
		$(".hidden_control").show();
		$(".print_control").hide();
         $(".receive_ctr").hide();
        mode = "edit";
         
        rows_click = $('#resultData').dataTable().fnGetPosition($(this).closest("tr").get(0));
        var data = $('#resultData').dataTable().fnGetData(rows_click);
       
        m_id = data[1];
        SetTableDetail(m_id,true);

        $.ajax({
            type: 'POST',
            cache: false,
            url: url,
            data: {"m": "getReceiveDetail", "id": m_id},
            success: function(data) {
                //alert(data);
                var obj = eval('(' + data + ')');
				$("#txtSupplier").html(obj['suppliername']);
                $("#txtPONo_").html(obj['po_no']);
				$("#txtRO").html(obj['ro_no']);
                $("#txtPurchaseDate").html(obj['purchasedate']);
               $("#txtOrderBy").html(obj['orderby']);
                 
            }
        });
    });
	$("#btnPrint").click(function(e){
		e.preventDefault(); 
		$("#frmReceive").get(0).setAttribute('action', 'rpt_purchase.php');
		$("#pid").val(m_id);
		$(this).closest('form').attr('target', '_blank').submit().removeAttr('target').removeAttr('action');
	});
	
    $(".btnView").live('click',function(){
        mode = "view";
		$(".print_control").show();
         $("#txtRO").hide();
         $(".receive_ctr").show();
        rows_click = $('#resultData').dataTable().fnGetPosition($(this).closest("tr").get(0));
        var data = $('#resultData').dataTable().fnGetData(rows_click);
       
        m_id = data[1];
		if (data[11]==5){	
			$("#btnCancel").html("ปิด");
			$(".hidden_control").hide();
		}
        SetTableDetail(m_id,false);
            
        $.ajax({
            type: 'POST',
            cache: false,
            url: url,
            data: {"m": "getReceiveDetail", "id": m_id},
            success: function(data) {
                
                var obj = eval('(' + data + ')');
                $("#txtPONo_").html(obj['po_no']);
                $("#txtPurchaseDate").html(obj['purchasedate']);
                $("#txtRONo_").html(obj['ro_no']);
                $("#txtReceiveDate").html(obj['receivedate']);
                $("#txtOrderBy").html(obj['orderby']);
                $("#txtReceiveBy").html(obj['receiveby']);
				$("#txtSupplier").html(obj['suppliername']);
            }
        });
    });
    $(".btnDel_detail").live('click', function() {
        var rows = $(this).closest("tr").get(0);
        rows_delete = $('#table_detail').dataTable().fnGetPosition(rows);
        $('#table_detail').dataTable().fnDeleteRow(rows_delete);
        $('#table_detail').dataTable().fnDraw();
    });
    
    $("#btnSearch").click(function() {
        var _ro = $("#txtRO_S").val();
        var _no = $("#txtPO_S").val();
        var _s = $("#cboReceive").val();
        var _df = $("#txtDateFrom_s").val();
        var _dt = $("#txtDateTo_s").val();
        var _emp = "";
        if ($('#txtEmployee').length)
            _emp = $("#txtEmployee").val();

        LoadData(_ro,_no, _s, _df, _dt, _emp);
    });

    $.get(url, {"m": "receive"}, function(data) {
        var obj = eval('(' + data + ')');
        if (obj !== null) {
            $.each(obj, function(index, text) {
                $("#cboReceive").append(
                        $('<option></option>').val(text).html(index)
                        );
            });
        }
    });

    $("#cboReceive").append($('<option></option>').val(0).html(' '));

    $.get(url, {"m": "pdtype"}, function(data) {
        var obj = eval('(' + data + ')');
        if (obj != null) {
            $.each(obj, function(index, text) {
                $("#cboType").append(
                        $('<option></option>').val(text).html(index)
                        );
            });
        }
    });
    //Main Table
    function LoadData(rq,no, status, df, dt, name) {
        $("#resultData tbody tr").remove();


        $('#resultData').dataTable({
            "bProcessing": true,
            "bFilter": false,
            "bLengthChange": false,
            "sAjaxSource": url,
            "oLanguage": {
                "sEmptyTable": "ไม่พบข้อมูล"
            },
            "bDestroy": true,
            "sServerMethod": "POST",
            "fnServerParams": function(aoData) {
                aoData.push({"name": "m", "value": "load_ro"},
                {"name": "rq","value":rq},
                {"name": "no", "value": no},
                {"name": "status", "value": status},
                {"name": "datefrom", "value": df},
                {"name": "dateto", "value": dt},
                {"name": "name", "value": name}

                );
            },
            "aoColumnDefs": [
                {"bVisible": false, "aTargets": [1]},
                {"bSortable": true, "aTargets": [2], "sClass": "center"},
                {"bSortable": true, "aTargets": [3], "sClass": "center"},
                {"bSortable": true, "aTargets": [4], "sClass": "text-left"},
                {"bSortable": true, "aTargets": [5], "sClass": "center"},
                {"bSortable": true, "aTargets": [6], "sClass": "center"},
                {"bSortable": true, "aTargets": [7], "sClass": "text-left"},
                {"bSortable": true, "aTargets": [8], "sClass": "text-right"},
                {"bSortable": true, "aTargets": [9], "sClass": "text-right"},
                {"bSortable": true, "aTargets": [10], "sClass": "center",
                    "mRender": function(data, type, full) {
						
                        var tmp = "";
                        if (full[11] == 3)
                            tmp = "<span class='label label-warning'>" + data + "</span>";
                        else if (full[11] == 5)
                            tmp = "<span class='label label-success'>" + data + "</span>";
                        else
                            tmp = data;
							
                        return tmp;
                    }

                },
                {"bVisible": false, "aTargets": [11]},
                {"aTargets": [12],
                    "sClass": "center",
                    "mData": null,
                    "mRender": function(data, type, full) {
                       if (full[11]==5)
                        return "<a href='#popup' data-toggle='modal'><img src='img/list.png' rel='tooltip' title='' data-original-title='ตรวจรายการ' class='btnView' style='cursor:pointer;'/></a>";
                        else 
                        return "<a href='#popup' data-toggle='modal'><img src='img/check_product.png' rel='tooltip' title='' data-original-title='ตรวจรายการ' class='btnCheck' style='cursor:pointer;'/></a>";
                    }
                },
                {"aTargets": [13],
                    "sClass": "center",
                    "mData": null,
                    "mRender": function(data, type, full) {
                        if (full[11] == 5)
                            return "<a href='#popupConfirm' data-toggle='modal'><img src='img/delete-file.png' class='btnDel' style='cursor:pointer;'/></a>";
                        else
                            return "";
                    }
                }

            ]
            , "fnDrawCallback": function(oSettings) {
                var that = this;
                /* Need to redo the counters if filtered or sorted */
                var iTotalRecords = oSettings.fnRecordsTotal();
                //alert(oSettings.aiDisplay.length + ' ' + iTotalRecords);

                if (iTotalRecords > 0) {
                    if (oSettings.bSorted || oSettings.bFiltered)
                    {
                        for (var i = 0, iLen = oSettings.aiDisplay.length; i < iLen; i++)
                        {
                            $('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[i] ].nTr).html(i + 1);
                        }
                    }
                }

            }
        });

    }


    $("#btnDelete").live('click', function() {

        var row_id = $('#resultData').dataTable().fnGetData(rows_delete);

        var id = row_id[1];

        $.ajax({
            type: 'POST',
            cache: false,
            url: url,
            data: {"m": "del", "id": id},
            success: function(data) {
                $("#popupConfirm").modal('hide');

                $('#resultData').dataTable().fnDeleteRow(rows_delete);
                $('#resultData').dataTable().fnDraw();
            }
        });

    });

    $(".btnDel").live('click', function() {
        var rows = $(this).closest("tr").get(0);
        rows_delete = $('#resultData').dataTable().fnGetPosition(rows);

    });

    
     
    
    function SetTableDetail(id,bln) {
        $("#table_detail").dataTable({"bProcessing": true,
            "bFilter": false,
            "bInfo": false,
            "bPaginate": false,
            "bLengthChange": false,
            "sAjaxSource": url,
            "oLanguage": {
                "sEmptyTable": "ไม่พบข้อมูล"
            },
            "bDestroy": true,
            "sServerMethod": "POST",
            "fnServerParams": function(aoData) {
                aoData.push({"name": "m", "value": "prd_detail"},
                {"name": "id", "value": id},
                {"name": "type", "value": "RO"}
                );
            },
            "aoColumnDefs": [
                {"bVisible": false, "aTargets": [1]},
                {"bSortable": true, "aTargets": [2], "sClass": "center"},
                {"bSortable": true, "aTargets": [3], "sClass": "text-left"},
                {"bSortable": true, "aTargets": [4], "sClass": "center"},
                {"bSortable": true, "aTargets": [5], "sClass": "center",
                    "mRender": function(data, type, full) {
                        
                        var tmp = "";
                        if (bln){                          
                            tmp = "<input type='textbox' class='span1 txtreceive_no text-right' name='txtro_amt' maxlength=4 value=" + full[5]+ " />";
                        }else 
                            tmp="<font style='color:red'>"+full[5]+"</font>";
                        return tmp;
                    }
                },
                {"bSortable": true, "aTargets": [6], "sClass": "text-right"},
                {"bSortable": true, "aTargets": [7], "sClass": "text-right"},
                {"bSortable": true, "aTargets": [8], "sClass": "text-right"} 
                 

            ], "fnDrawCallback": function(oSettings) {
                var that = this;
                /* Need to redo the counters if filtered or sorted */
                var iTotalRecords = oSettings.fnRecordsTotal();
                //alert(oSettings.aiDisplay.length + ' ' + iTotalRecords);

                if (iTotalRecords > 0) {
                    if (oSettings.bSorted || oSettings.bFiltered)
                    {
                        for (var i = 0, iLen = iTotalRecords; i < iLen; i++)
                        {
                            $('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[i] ].nTr).html(i + 1);
                        }
                    }
                }

            }

        });

    }
});


